package com.jx.smartbot.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.jx.smartbot.VO.GoComMessage4Text;
import com.jx.smartbot.VO.GoComMessageEPP;
import com.jx.smartbot.VO.GroupPostMessage;
import com.jx.smartbot.VO.PostMessage;
import com.jx.smartbot.VO.ReturnMessage;
import com.jx.smartbot.VO.Token;
import com.jx.smartbot.entity.WpTt;
import com.jx.smartbot.repository.WpTtRepository;
import com.jx.smartbot.service.IRedisService;
import com.jx.smartbot.service.SystemSuperApp;
import com.jx.smartbot.util.JacksonUtil;
import com.jx.smartbot.util.JaxbUtil;

import springfox.documentation.annotations.ApiIgnore;
@ApiIgnore
@RestController
public class BotController implements ErrorController {
	
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(BotController.class);
	private static final String urlstr = "http://172.20.95.11:9901/gocomapi/rest/";
	//private static final String urlstr_super = "http://172.20.95.11:9901/superapp/";
	private static final String PATH = "/error";
	private Map<String, String> users = new HashMap<>();
	Token token = null;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	SystemSuperApp systemSuperApp;
	@Autowired
	WpTtRepository wpTtRepository;
	@Autowired
	IRedisService redisService;
	private StringBuffer appid_token(String appid){
		StringBuffer sb=new StringBuffer();
		sb.append("access_token=");
		sb.append(systemSuperApp.accessToken().getAccessToken());
		sb.append("&");
		sb.append("token_type=");
		sb.append("superapp");
		sb.append("&");
		sb.append("appid=");
		sb.append(appid);
		return sb;
	}
	private String personAppid(){
		return appid_token("xw7snhdayl").toString();
	}
	private String groupbotAppid(){
		return appid_token("grpifp5o6wq3z1").toString();
		//return appid_token("grpix2guz18x9s").toString();
	}
	private String assistantAppid(){
		return appid_token("7xwbqnbm6y").toString();
	}
	//assistant
	@RequestMapping(value = "assistant_t", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object assistant(HttpServletRequest request) {
		try {
			PostMessage postMessage = JaxbUtil.converyToJavaBean(reqContent(request), PostMessage.class);
			//String r = this.users.get(postMessage.getFromUserName());
			//String rt = restTemplate.postForObject(urlstr + "message/single/send?"+assistantAppid(),takeGoComMessage4Text(postMessage),String.class);
			String rt = restTemplate.postForObject(urlstr + "message/single/send/status?"+assistantAppid(),takeGoComMessage4Text(postMessage),String.class);
			logger.info("=======111======{}",rt);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "groupbot", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object group_bot2(HttpServletRequest request) {
		try {
			GroupPostMessage postMessage=JaxbUtil.converyToJavaBean(reqContent(request),GroupPostMessage.class);//"message/single/send/status?"
			String rt = restTemplate.postForObject(urlstr + "message/groupapp/send?"+groupbotAppid(),takeGoComMessage4Text2(postMessage),String.class);
			//String rt = restTemplate.postForObject(urlstr + "message/groupapp/send/status?"+groupbotAppid(),takeGoComMessage4Text2(postMessage),String.class);
			logger.info("============={}",rt);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping(value = "personcallback1.json", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object callback(@RequestBody PostMessage postMessage,
			HttpServletRequest request) {
		return null;
	}
	@RequestMapping(value = "personcallback.json", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object callback(HttpServletRequest request) {
		try {
			PostMessage postMessage = JaxbUtil.converyToJavaBean(reqContent(request), PostMessage.class);
			//String r = this.users.get(postMessage.getFromUserName());
			String rt = restTemplate.postForObject(urlstr + "message/single/send?"+personAppid(),takeGoComMessage4Text(postMessage),String.class);
			//String rt = restTemplate.postForObject(urlstr + "message/single/send/status?"+personAppid(),takeGoComMessage4Text(postMessage),String.class);
			logger.info("url========== :{}",urlstr + "message/single/send?"+personAppid());
			logger.info("return mesage :{}",rt);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@RequestMapping(value = "groupbot1", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object group_bot(HttpServletRequest request) {
		try {
			String sss=reqContent(request);
			GroupPostMessage postMessage=JaxbUtil.converyToJavaBean(sss,GroupPostMessage.class);
			MultiValueMap<String, String> requestEntity = new  LinkedMultiValueMap<>();
/*			logger.info(sss);
			
			requestEntity.add("appid","supu3fg612wtd"); 
			requestEntity.add("secret","1uj2mte5");*/
			//restTemplate.get
			//String r=restTemplate.getForObject(urlstr+"superapp/access_token",String.class,requestEntity);
/*			String r=restTemplate.postForObject(urlstr+"superapp/access_token",requestEntity,String.class);
			logger.info(r);*/
			//String r=restTemplate.getForObject(urlstr_super+"access_token",requestEntity,String.class);
			//token=JacksonUtil.readValue(r, Token.class); 
			
		//	ReturnMessage rt = restTemplate.postForObject(urlstr + "message/groupapp/send?access_token=" + token.getAccessToken(), takeGoComMessage4Text(postMessage),
			//		ReturnMessage.class);
			//token_type=superapp&appid=hfuag434fha
			requestEntity.clear();
			requestEntity.add("access_token",token.getAccessToken()); 
			requestEntity.add("token_type","superapp");
			requestEntity.add("appid","grpifp5o6wq3z1");
		//String rt = restTemplate.postForObject(urlstr + "message/groupapp/send?access_token=" + token.getAccessToken(), requestEntity,takeGoComMessage4Text(postMessage),String.class);
			StringBuffer sb=new StringBuffer();
			
			//sb.append("&");
			sb.append("access_token=");
			//sb.append(token.getAccessToken());
			sb.append(systemSuperApp.accessToken());
			sb.append("&");
			sb.append("token_type=");
			sb.append("superapp");
			sb.append("&");
			sb.append("appid=");
			sb.append("grpifp5o6wq3z1");
			String rt = restTemplate.postForObject(urlstr + "message/groupapp/send?"+sb.toString(),takeGoComMessage4Text(postMessage),String.class);
			logger.info("============={}",rt);
	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "groupbots", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object group_bots(HttpServletRequest request) {
		try {
			String t = reqContent(request);

			logger.info(t);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "callback2.json", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	public Object callback2(HttpServletRequest request) {
		try {
			PostMessage postMessage = JaxbUtil.converyToJavaBean(reqContent(request), PostMessage.class);
			String r = this.users.get(postMessage.getFromUserName());
			if (r == null) {
				MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
				// ID：xw7snhdayl 密码：1uj2mte5
				requestEntity.add("appid", "bzlhgn93z5");
				requestEntity.add("secret", "x1awpqei");
				r = restTemplate.postForObject(urlstr + "access_token", requestEntity, String.class);
				users.put(postMessage.getFromUserName(), r);
				token = JacksonUtil.readValue(r, Token.class);
			}
			if (token == null) {
				return "";
			}
			ReturnMessage rt = restTemplate.postForObject(urlstr + "message/single/send?access_token=" + token.getAccessToken(),takeMessage(postMessage),
					ReturnMessage.class);
			if (rt.getErrcode() != 0) {
				// System.out.println("----end
				// error----------------"+postMessage.getFromUserName());
				logger.error(JacksonUtil.toJSon(rt));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	@Override
	public String getErrorPath() {
		// TODO Auto-generated method stub
		return PATH;
	}

	@RequestMapping(value = PATH, produces = { "application/json" })
	public String error() {
		return "Error handling";
	}
	
	/*private Reader reqContent2Reader(HttpServletRequest request) throws IOException {
		return new InputStreamReader( request.getInputStream(),"utf-8");
	}*/

	private String reqContent(HttpServletRequest request) throws IOException {
		int len = request.getContentLength();
		byte buffer[] = new byte[len];
		InputStream in = request.getInputStream();
		int total = 0;
		int once = 0;
		while ((total < len) && (once >= 0)) {
			once = in.read(buffer, total, len);
			total += once;
		}
		//String  s=new String(buffer, "utf-8");
	//	logger.info(s);
		return new String(buffer, "utf-8");
	}
	private GoComMessage4Text takeGoComMessage4Text2(GroupPostMessage post) {
		GoComMessage4Text gtext = new GoComMessage4Text();
		gtext.setTouser(post.getGroup());
		int id=post.getMsgId();
		gtext.setMsgId(id);
		String content=post.getContent();
		
	/*	String str="";
	str+="<script type='text/javascript'> ";
		str+="function submitform() ";
		str+="{ ";
		str+="    document.forms['myform'].submit() ";
		str+="} ";
		str+="</script> ";
		str+="<form id='myform' action='http://172.20.95.36:8080/wp/groups?token=%token%' method='post'> ";
		str+="<input type='text' name='content' value='"+content+"'> ";
		str+="<a href='javascript: submitform()'>"+content+"</a> ";
		str+="</form> ";*/
		
		
		if(content.startsWith("A")){
			gtext.setContent(content+" : <a href='http://172.20.95.37:8080/biz/wp/tools?token=AAA'>token send11111111</a>");	
			letToken("AAA","zhouzg@lxyt","pc");
		}else if(content.startsWith("S")){
			gtext.setContent(content+" : <a href='http://172.20.95.37:8080/biz/wp/sharing?token=SSS'>token send3333333333333</a>");	
			letToken("SSS","lwd@lxyt","pc");
		}else{
		gtext.setContent(content+" : <a href='http://172.20.95.37:8080/biz/wp/groups?token=BBB&groupid=%groupid%'>token send2222222222222</a>");	
		letToken("BBB","test@lxyt","pc");
		}
		//http://172.20.95.36/wpclient/
		// gtext.setContent(str);	
		 return gtext;
	}
	private void letToken(String key,String user,String device){
		//redisService.hSet(key, "userid", "zhouzg@lxyt");
		//redisService.hSet(key, "device", "pc");
		redisService.hSet(key, "userid", user);
		redisService.hSet(key, "device", device);
	}
	
	private GoComMessage4Text takeGoComMessage4Text(GroupPostMessage post) {
		long ii=wpTtRepository.count();
		logger.info("---------------0000000000000-------{}-------{}",ii,post.getMsgId());
		//WpTt wpTt= wpTtRepository.findById(1);
		WpTt wpTt= wpTtRepository.findOne(1L);
		if(wpTt !=null){
			logger.info("---------------111--------------->{}",wpTt.getName());
		}else{
			logger.info("---------------222----------------");
		}
		GoComMessage4Text gtext = new GoComMessage4Text();
		gtext.setTouser(post.getGroup());
		//logger.info("-------------------------------->{}",wpTt.getName());
		 gtext.setContent("<a href='https://www.baidu.com'>"+wpTt.getContent()+"</a>");
		//gtext.setContent("<H1>你好==========</H1>");
		return gtext;
	}
	/*private GoComMessage4Text takeGoComMessage4Text2(GroupPostMessage post) {
		GoComMessage4Text gtext = new GoComMessage4Text();
		gtext.setTouser(post.getFromUserName());
		// gtext.setContent("<a href='https://www.baidu.com'>bddu</a>");
		gtext.setContent("<H1>你好</H1>");
		return gtext;
	}*/
	private GoComMessage4Text takeGoComMessage4Text(PostMessage post) {
		GoComMessage4Text gtext = new GoComMessage4Text();
		gtext.setTouser(post.getFromUserName());
		
		// gtext.setContent("<a href='https://www.baidu.com'>bddu</a>");
		logger.info("--------post.getFromUserName()--------------{}",post.getFromUserName());
		gtext.setContent("<H1>你好</H1>");
		return gtext;
	}

	private GoComMessageEPP takeMessage(PostMessage post) {
		logger.info(post.getMsgType());
		logger.info(post.getContent());
		if (post.getMsgType().equals("text")) {
			return takeGoComMessage4Text(post);
		}
		return null;
	}

}
